<template>
  <div class="home-container">
    <!-- 整体卡片 -->
    <div class="school-card">
      <!-- 头部学校信息 -->
      <div class="school-header">
        <div class="school-logo">
          <div class="logo-placeholder">
            <img :src="userInfo.avatar" alt="logo" />
          </div>
        </div>
        <div class="school-info">
          <div>
            <h1 class="school-name">{{ userInfo.name }}</h1>
            <p class="text-base text-gray-500">{{ greeting }}</p>
          </div>

          <div class="time-display">{{ currentTime }}</div>
        </div>
      </div>

      <!-- 统计数据卡片 -->
      <div class="stat-cards">
        <div class="stat-card">
          <div class="stat-number">{{ statData.personCount }}</div>
          <div class="stat-label">学生教职工人数</div>
        </div>
        <div class="stat-card">
          <div class="stat-number">{{ statData.ClassCount }}</div>
          <div class="stat-label">班级数</div>
        </div>
        <div class="stat-card">
          <div class="stat-number">{{ statData.courseCount }}</div>
          <div class="stat-label">课程数量</div>
        </div>
        <div class="stat-card">
          <div class="stat-number">{{ statData.rounds }}</div>
          <div class="stat-label">选课数量</div>
        </div>
      </div>
    </div>

    <!-- 红框内的卡片区域 -->
    <div class="card-container">
      <!-- 左侧卡片：课程进度 -->
      <div class="info-card">
        <div class="card-header">
          <h3 class="card-title">课程选课情况</h3>
          <span class="view-more">查看 &gt;</span>
        </div>
        <div class="card-content pt-4">
          <div
            v-for="(course, index) in courseList"
            :key="index"
            class="mb-4 px-4"
          >
            <div class="flex justify-between items-center mb-1">
              <span class="text-sm font-medium text-gray-700">{{
                course.courseName
              }}</span>
              <span class="text-xs text-gray-500"
                >{{
                  calculatePercentage(course.chooseNum, course.personMax)
                }}%</span
              >
            </div>
            <div class="w-full bg-gray-200 rounded-full h-3">
              <div
                class="h-3 rounded-full"
                :class="getProgressBarColor(course.chooseNum, course.personMax)"
                :style="{
                  width: `${calculatePercentage(
                    course.chooseNum,
                    course.personMax
                  )}%`,
                }"
              ></div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧卡片：已经开始选课 -->
      <div class="info-card">
        <div class="card-header">
          <h3 class="card-title">选课已开放</h3>
          <span class="view-more">查看 &gt;</span>
        </div>
        <div class="card-content">
          <table class="data-table">
            <thead>
              <tr>
                <th>选课轮次</th>
                <th>选课开始时间</th>
                <th>选课结束时间</th>
                <th>状态</th>
              </tr>
            </thead>
            <tbody>
              <!-- 如果没有数据，显示占位行 -->
              <tr v-for="item in roundList">
                <td>{{ item.name }}</td>
                <td>{{ formatDate(item.startTime) }}</td>
                <td>{{ formatDate(item.endTime) }}</td>
                <td>
                  <span :class="getStatusClass(item)">{{
                    getStatusText(item)
                  }}</span>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { gethomedata } from '@/api/home.js'
import { useUserStore } from '@/stores/user.js'
import { getroundlist } from '@/api/round.js'
import { getcourseDetails } from '@/api/courseDetails.js'
import { ElMessage } from 'element-plus'

// 用户数据
const userInfo = useUserStore().userInfo

// 当前时间
const currentTime = ref('')
const currentHour = ref(0)

// 问候语
const greeting = computed(() => {
  const hour = currentHour.value
  if (hour >= 5 && hour < 12) {
    return '早上好!'
  } else if (hour >= 12 && hour < 14) {
    return '中午好!'
  } else if (hour >= 14 && hour < 18) {
    return '下午好!'
  } else {
    return '晚上好!'
  }
})

// 格式化时间函数
const formatTime = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')

  // 更新当前小时数用于问候语
  currentHour.value = now.getHours()

  return `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`
}

// 定时器
let timer = null

// 更新时间
const updateTime = () => {
  currentTime.value = formatTime()
}

// 统计数据
const statData = ref({})
// 选课轮次列表
const roundList = ref([])
// 选课列表
const courseList = ref([])

// 获取选课轮次列表
const getRoundList = async () => {
  const { code, data, msg } = await getroundlist()
  if (code !== 200) {
    ElMessage.error(msg)
  }
  roundList.value = data.records
}

// 获取选课列表
const getCourseList = async () => {
  const { code, data, msg } = await getcourseDetails()
  if (code !== 200) {
    ElMessage.error(msg)
  }
  courseList.value = data.records
}

// 格式化日期函数
const formatDate = (dateString) => {
  if (!dateString) return ''

  try {
    const date = new Date(dateString)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')

    return `${year}-${month}-${day}`
  } catch (error) {
    return dateString
  }
}

// 获取首页数据
const getHomeData = async () => {
  const { code, data, msg } = await gethomedata()
  if (code !== 200) {
    throw new Error(msg)
  }
  statData.value = data
  statData.value.rounds = data.roundName ? data.roundName.length : 0
  console.log(data)
}

// 获取选课状态文本
const getStatusText = (item) => {
  const now = new Date()
  const startTime = new Date(item.startTime)
  const endTime = new Date(item.endTime)

  if (now < startTime) {
    return '即将开始'
  } else if (now > endTime) {
    return '已结束'
  } else {
    return '进行中'
  }
}

// 获取选课状态样式类
const getStatusClass = (item) => {
  const now = new Date()
  const startTime = new Date(item.startTime)
  const endTime = new Date(item.endTime)

  if (now < startTime) {
    return 'text-blue-500 font-bold'
  } else if (now > endTime) {
    return 'text-gray-500 font-bold'
  } else {
    return 'text-green-500 font-bold'
  }
}

// 计算百分比
const calculatePercentage = (current, max) => {
  if (!max || max === 0) return 0
  const percentage = (current / max) * 100
  return percentage.toFixed(2)
}

// 根据百分比获取进度条颜色
const getProgressBarColor = (current, max) => {
  if (!max || max === 0) return ''

  const percentage = (current / max) * 100

  if (percentage < 30) {
    return 'progress-blue' // 低选课率
  } else if (percentage < 70) {
    return 'progress-yellow' // 中等选课率
  } else {
    return 'progress-green' // 高选课率
  }
}

// 组件挂载时启动定时器
onMounted(() => {
  updateTime() // 立即更新一次
  timer = setInterval(updateTime, 1000) // 每秒更新一次
  // 获取首页数据
  getHomeData()
  // 获取选课轮次列表
  getRoundList()
  // 获取选课列表
  getCourseList()
})

// 组件卸载前清除定时器
onBeforeUnmount(() => {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
})
</script>

<style lang="less" scoped>
.home-container {
  background: linear-gradient(135deg, #ebfff9, #fcf0fb, #f2ffed);
  min-height: 100%;
  // padding: 20px;
}

.school-card {
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  overflow: hidden;
  margin-bottom: 20px;
}

.school-header {
  display: flex;
  align-items: center;
  padding: 20px;
  padding-bottom: 0;
}

.school-logo {
  margin-right: 20px;
}

.logo-placeholder {
  overflow: hidden;
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background-color: #e0e7ff;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #4f46e5;
  font-size: 24px;
  img {
    transform: scale(1.3);
  }
}

.school-info {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.school-name {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin: 0;
}

.time-display {
  font-weight: bold;
  font-size: 20px;
  color: #666;
  margin-right: 20px;
  white-space: nowrap;
}

.school-term {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.stat-cards {
  display: flex;
  justify-content: space-between;
  padding: 0 20px;
  background-color: transparent;
}

.stat-card {
  flex: 1;
  text-align: center;
  padding: 20px 0;
  position: relative;
}

.stat-card:not(:last-child)::after {
  content: '';
  position: absolute;
  right: 0;
  top: 20%;
  height: 60%;
  width: 1px;
  background-color: #eee;
}

.stat-number {
  font-size: 36px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

/* 红框区域卡片样式 */
.card-container {
  display: flex;
  gap: 20px;
  margin-top: 20px;
}

.info-card {
  height: 46vh;
  overflow: hidden;
  flex: 1;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #eee;
}

.card-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin: 0;
}

.view-more {
  font-size: 14px;
  color: #999;
  cursor: pointer;
}

.card-content {
  padding-bottom: 10px;
  max-height: 40vh;
  overflow-y: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th,
.data-table td {
  padding: 12px 16px;
  text-align: left;
  font-size: 14px;
  border-bottom: 1px solid #eee;
}

.data-table th {
  background-color: #f8f9fa;
  color: #666;
  font-weight: normal;
}

.data-table tr:last-child td {
  border-bottom: none;
}

.data-table tr:hover td {
  background-color: #f8f9fa;
}

/* 自定义滚动条样式 */
.card-content::-webkit-scrollbar {
  width: 6px;
}

.card-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.card-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.card-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 删除自定义状态样式，改用Tailwind CSS */
/* 
.status-ongoing {
  color: #67c23a;
  font-weight: bold;
}

.status-upcoming {
  color: #409eff;
  font-weight: bold;
}

.status-ended {
  color: #909399;
  font-weight: bold;
}
*/

/* 进度条渐变色样式 */
.progress-blue {
  background: linear-gradient(90deg, #4299e1, #3182ce);
}

.progress-yellow {
  background: linear-gradient(90deg, #f6ad55, #ed8936);
}

.progress-green {
  background: linear-gradient(90deg, #68d391, #38a169);
}
</style>
